package org.apache.ibatis.ibator.plugins;

import java.util.List;

import org.apache.ibatis.ibator.api.IbatorPluginAdapter;
import org.apache.ibatis.ibator.api.IntrospectedTable;
import org.apache.ibatis.ibator.api.dom.java.FullyQualifiedJavaType;
import org.apache.ibatis.ibator.api.dom.java.InnerClass;
import org.apache.ibatis.ibator.api.dom.java.Method;
import org.apache.ibatis.ibator.api.dom.java.Parameter;
import org.apache.ibatis.ibator.api.dom.java.TopLevelClass;

/**
 * 为查询条件增加别名
 * 
 * @author liwb 2016年1月27日 下午2:11:30
 */
public class AliasExamlePlugin extends IbatorPluginAdapter {

    public AliasExamlePlugin() {
        super();
    }

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
            IntrospectedTable introspectedTable) {
        InnerClass criteria = null;
        // first, find the Criteria inner class
        for (InnerClass innerClass : topLevelClass.getInnerClasses()) {
            if ("GeneratedCriteria".equals(innerClass.getType().getShortName())) { //$NON-NLS-1$
                criteria = innerClass;
                break;
            }
        }

        if (criteria == null) {
            // can't find the inner class for some reason, bail out.
            return true;
        }
        List<Method> methods = criteria.getMethods();
        String methodName, firstLine, param;
        int subIndex, subIndexEnd;
        StringBuilder sb = new StringBuilder();
        for (Method method : methods) {
            methodName = method.getName();
            if (methodName.startsWith("and")) {
                method.addParameter(new Parameter(FullyQualifiedJavaType
                        .getStringInstance(), "alias"));
                List<String> bodyLines = method.getBodyLines();
                if (bodyLines.size() > 1) {
                    sb.setLength(0);
                    firstLine = bodyLines.get(0);
                    subIndex = firstLine.indexOf("\"");
                    subIndexEnd = firstLine.indexOf(" ", 14);
                    param = firstLine.substring(subIndex + 1, subIndexEnd);
                    sb.append(firstLine.substring(0, subIndex));
                    sb.append("(null == alias ? \"");
                    sb.append(param);
                    sb.append("\" : alias + \".\" + \"");
                    sb.append(param);
                    sb.append("\") + ");
                    sb.append(firstLine.substring(subIndex));
                    bodyLines.add(0, sb.toString());
                    method.setBodyLine(0, sb.toString());
                }
            }
        }

        return true;
    }
}
